package Schema::Result::CustomEnum;

use strict;
use warnings;
use utf8;

use base qw/DBIx::Class::Core/;

__PACKAGE__->table('CustomEnum');
__PACKAGE__->add_columns( 
    Id => { data_type => 'integer', is_auto_increment => 1 }, 
    ProjectId  => {},
    Name  => {},
    Comment  => {},
);
__PACKAGE__->set_primary_key('Id');
__PACKAGE__->has_many(Items => 'Schema::Result::EnumItem', 'CustomEnumId', { cascade_delete => 1 });

# 创建自定义枚举
sub Create{
    my ($class, $schema, $params) = @_;

    return $schema->txn_do(sub {
        my $newCustomEnum = $schema->resultset("CustomEnum")->create(
            {
                ProjectId => $params->{ProjectId},
                Name => $params->{Name},
                Comment => $params->{Comment},
            }
        );

        if (exists $params->{Items} && ref $params->{Items} eq 'ARRAY') {
            foreach my $item (@{$params->{Items}}) {
                $newCustomEnum->create_related(
                    'Items',
                    {
                        Key => $item->{key},
                        Value => $item->{value},
                        Comment => $item->{comment},
                    }
                )
            }
        }

        return $newCustomEnum;

    });
}

# 修改自定义枚举
sub Modify{
    my ($self, $name, $comment, $items) = @_;

    # 0 表示失败 1 表示成功
    my $result = 0;
    # 失败原因
    my $reason = '';

    eval {
        $self->update({
                Name => $name,
                Comment => $comment,
            });

        $self->Items->delete_all;

        foreach my $item(@$items) {
            $self->create_related( 'Items', {
                Key => $item->{key},
                Value => $item->{value},
                Comment => $item->{comment},
            });
        }
        $result = 1;
    };

    if($@){
        $reason = "Failed to update configuration: $@";
        $result = 0;
    }

    return { Success => $result, Reason => $reason };
}

# 删除
sub Delete {
    my ($self) = @_;

    $self->delete;
}

1;
